//
//  GYKeyViewController.m
//  LockManagement
//
//  Created by apple on 2018/7/21.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYKeyViewController.h"
#import "GYKeyTableViewCell.h"
#import "GYKey.h"
#import "GYBleDataManager.h"
#import "GYBleOperationManager.h"

@interface GYKeyViewController ()<UITableViewDelegate,UITableViewDataSource>

/** key表格 */
@property (nonatomic, strong) UITableView *keyTbaleView;

/** 表格数据源 */
@property (nonatomic, strong) NSArray *keyLists;

/** 蓝牙数据收发类 */
@property (nonatomic, strong) GYBleOperationManager *operationManager;
@end

@implementation GYKeyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.keyTbaleView reloadData];
    //监听蓝牙收到数据
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receivemessage:) name:BLEReceeiveMessage object:nil];
    
    [self getKeyElectric];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:BLEReceeiveMessage object:nil];
}

- (void)receivemessage:(NSNotification *)noti {
    NSLog(@"ble receive message=========%@",noti.object);
    NSData *messageData = noti.object;
    
    NSData *data = [messageData subdataWithRange:NSMakeRange(2, 1)];
    if ([[GYBleDataManager convertDataToHexStr:data] intValue] == 6) {
        
        NSData *elcdata = [messageData subdataWithRange:NSMakeRange(5, 1)];//钥匙的电量
        
//        NSData *mauData = [messageData subdataWithRange:NSMakeRange(6, 1)];//厂家
//        NSData *verData = [messageData subdataWithRange:NSMakeRange(7, 2)];//版本号
//        NSData *desData = [messageData subdataWithRange:NSMakeRange(9, 1)];//加密方式
        NSLog(@"key elc=========%%%@",[GYBleDataManager convertDataToHexStr:elcdata]);
        [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"蓝牙钥匙电量:%%%@",[GYBleDataManager convertDataToHexStr:elcdata]]];
    }
}

- (void)getKeyElectric{
    //1.通过蓝牙查询设备的mac地址,  或则蓝牙名字后面 的后6位是 mac地址
    if (self.operationManager.connectType == deviceConntTypeSuccess) {
        //0.查询链接蓝牙钥匙的电量
        for (GYKey *model in self.keyLists) {
            NSLog(@"model.mac======%@",model.keyMac);
            
            NSArray *macs = [model.keyMac componentsSeparatedByString:@":"];
            NSString *macString =@"";
            for (NSString *string in macs) {
                macString = [macString stringByAppendingString:string];
            }
            //NSLog(@"macString==========%@",macString);
            NSString *periphrealName = self.operationManager.periphreal.name;
            NSString *mac = [periphrealName substringWithRange:NSMakeRange(periphrealName.length-12, 12)];
            NSLog(@"mac==========%@   str======%@",mac,macString);
            if ([macString isEqualToString:mac]) {
                NSLog(@"发送查询名利的电量");
                //2.根据mac地址  比较  然后查询指定钥匙的电量
                NSData *elcData = [GYBleDataManager getKeyElc];
                [self.operationManager sendMessage:elcData];
                
                //3.储存该钥匙的ID
                SETOBJ(@(model.keyID), @"keyID");
                
                //4.然后结束循环
                break;
            }
            
        }
    }
}

- (void)setupUI {
    self.view.backgroundColor = RGBColor(249, 249, 249);
    [self.view addSubview:self.keyTbaleView];
    
    //加载数据
    [self loadData];
    
    self.keyTbaleView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
}

- (void)loadData {
    [GYKey getKeyListsCurrent:@"1" pageSize:@"99" success:^(NSArray *keys) {
        [self.keyTbaleView.mj_header endRefreshing];
        
        self.keyLists = keys;
        [self.keyTbaleView reloadData];
        
    } error:^(NSError *error) {
        
    }];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.keyTbaleView.frame = self.view.bounds;
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.keyLists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYKeyTableViewCell *cell = [GYKeyTableViewCell cellWithTableView:tableView];
    cell.keyModel = self.keyLists[indexPath.row];
    NSString *periphrealName = self.operationManager.periphreal.name;
    NSString *mac = [periphrealName substringWithRange:NSMakeRange(periphrealName.length-12, 12)];
    cell.connectKeyMac = mac;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYKeyTableViewCell *cell = [GYKeyTableViewCell cellWithTableView:tableView];
    
    return [cell cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -- 懒加载

- (UITableView *)keyTbaleView {
    if (!_keyTbaleView) {
        _keyTbaleView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _keyTbaleView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _keyTbaleView.dataSource = self;
        _keyTbaleView.delegate = self;
        
    }
    return _keyTbaleView;
}

- (GYBleOperationManager *)operationManager {
    if (!_operationManager) {
        _operationManager = [GYBleOperationManager shareOperationManager];
    }
    
    return _operationManager;
}
@end
